<template>
    <div>
      <!-- 商品参数 -->
      <!-- 面包屑 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>商品参数</el-breadcrumb-item>
      </el-breadcrumb>

      <el-card>
        <el-alert title="注意: 只允许为第三级分类设置相关参数!" type="error" show-icon></el-alert>
        <el-form label-width="120px" class="demo-ruleForm">
        <el-form-item label="选择列表分类：">
        <el-cascader
          placeholder="请选择"
          :props="forclass"
          :options="goodsclass"
          filterable
          v-model='paramValue'
          @change ='changeParam'
        ></el-cascader>
        </el-form-item></el-form>
        <!-- TABS标签 -->
        <el-tabs v-model="closename" @tab-click="handleClick">
          <el-tab-pane label="动态参数" name="only">
            <el-button type="primary" :disabled = 'ison' @click="addopen">添加动态参数</el-button>
           
            <el-table
            :data="paramData"
            border
            style="width: 100%;margin-top:20px">
            <el-table-column type="expand" class="column">
              <template slot-scope="scope">

                  <el-tag
                    :key="scope.row.id"
                    v-for="(tag,i) in scope.row.attr_vals"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(i,scope.row)">
                    {{tag}}
                  </el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ 参数属性</el-button>
                
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-search" size ='small' @click="modParam(scope.row)">修改</el-button>
                <el-button type="danger" icon="el-icon-delete" size ='small' @click="deParam(scope.row)">删除</el-button>
              </template>
            </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="静态参数" name="many">
            <!--  -->
            <el-button type="primary" :disabled = 'ison' @click="addopen">添加静态参数</el-button>
            <!-- 静态参数列表 -->
             <el-table
            :data="paramData"
            border
            style="width: 100%;margin-top:20px">
            <el-table-column type="expand" class="column">
              <template slot-scope="scope">
                
                  <el-tag
                    :key="scope.row.id"
                    v-for="(tag,i) in scope.row.attr_vals"
                    closable
                    @close="handleClose(i,scope.row)">
                    {{tag}}
                  </el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ 参数属性</el-button>
                
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-search" size ='small' @click="modParam(scope.row)">修改</el-button>
                <el-button type="danger" icon="el-icon-delete" size ='small' @click="deParam(scope.row)">删除</el-button>
              </template>
              
            </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-card>

       <!-- 添加动态参数弹窗 -->
            <el-dialog
              :title="'添加'+title"
              :visible.sync="doParam"
              width="30%">
              <el-form :model="paramName" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="参数名称" prop="attr_name">
                  <el-input v-model="paramName.attr_name"></el-input>
                </el-form-item>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button @click="doParam = false">取 消</el-button>
                <el-button type="primary" @click="sureAddParam">确 定</el-button>
              </span>
            </el-dialog>
      <!-- 修改分类参数弹窗 -->
      <el-dialog
        title="提示"
        :visible.sync="modParamVis"
        width="30%">
        <el-form :model="modParamName" :rules="rules" ref="modParamName" label-width="100px" class="demo-ruleForm">
                <el-form-item label="参数名称" prop="attr_name">
                  <el-input v-model="modParamName.attr_name"></el-input>
                </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="backmod">取 消</el-button>
          <el-button type="primary" @click="suremod">确 定</el-button>
        </span>
      </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
           goodsclass: [],
           forclass:{
             value:'cat_id',
             label:'cat_name',
             children:'children',
           },
           closename:'only',
           paramData:[],
           paramValue:[],
           paramId:'',//分类id
           isok:'only',
           inParam:[],
           dynamicTags:[],
           rowID:'',
           ison:true,
           rules: {
              attr_name: [
                { required: true, message: '请输入参数名称', trigger: 'blur' },
                { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
              ]},
          paramName:{
            attr_name:''
          },
          doParam:false,
          modParamVis:false,
          modParamName:{
            attrId:'',
            attr_name:''
          }
          // title:''
        };
    },
    computed:{
      title(){
        if(this.isok === 'only') return "动态参数"
        return '静态参数'
      }
    },
    created() {

    },
    mounted() {
      this.goodsParamData()
    },
    methods: {
      async goodsParamData(){//获取分类列表
        const {data:res} = await this.$http.get('categories')
        // console.log(res);
        if(res.meta.status =! 200) return this.$message.error('获取分类列表失败')
        this.goodsclass = res.data
      },
      //tabs标签
      handleClick(tab, event) {
        // console.log(tab);
        this.isok = tab.paneName
        if(this.paramValue.length > 0) return this.golist()
        return
        
      },
      //选择框事件
      changeParam(){
        console.log(this.paramValue);
        this.paramId = this.paramValue[2]
        if(this.paramValue.length < 3) return this.paramValue = []
        // console.log(this.isok);
        this.ison =false
        this.golist()
      },
      //获取参数列表
      async golist(){
        
        const {data:res} = await this.$http.get(`categories/${this.paramId}/attributes`,{params:{sel:this.isok}})
        res.data.forEach(item => {
          item.attr_vals= item.attr_vals.split(',')
          item.inputVisible = false
          item.inputValue = ''
        });
        // console.log(res.data);
        if(res.meta.status =! 200) return this.$message.error(获取参数失败)
        this.paramData =res.data
      },
      // 新加参数属性
      showInput(row){
        row.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      //新加的参数输入框事件.失去焦点
      handleInputConfirm(row) {
        if(row.inputValue.trim().length === 0){
          row.inputValue =''
          row.inputVisible =false
          return
        }
        row.attr_vals.push(row.inputValue.trim())
        row.inputValue = ''
        row.inputVisible =false
        // console.log(row.attr_sel);
        this.govals(row)
      },
      async govals(row){//更新参数属性
        const {data:res} = await this.$http.put(`categories/${this.paramId}/attributes/${row.attr_id}`,
        {attr_name:row.attr_name,
         attr_sel:row.attr_sel,
         attr_vals:row.attr_vals.join(',')})
        if(res.meta.status =! 200) return this.$message.error('更新参数属性失败')
        this.$message.success('更新参数属性成功')
        // console.log(res);
      },
      //删除参数属性
      handleClose(i,row){
        this.$confirm('删除该参数属性, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          row.attr_vals.splice(i,1)
          this.govals(row)
          this.$message.success('已删除该参数属性')
          
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
      // 点击添加参数
      addopen(){
        this.doParam =true
        
      },
      // 确定添加参数
      sureAddParam(){
        this.$refs.ruleForm.validate(async (valid) => {
          if (!valid) return
          const {data:res} = await this.$http.post(`categories/${this.paramId}/attributes`,
          {attr_name:this.paramName.attr_name,attr_sel:this.isok})
          if(res.meta.status =! 200) return this.$message.error('添加参数失败')
          this.$message.success('添加参数成功')
          this.doParam = false
          this.golist()
        })
      },
      //删除该分类
      deParam(row){
        console.log(row);
         this.$confirm('删除该参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {data:res} = await this.$http.delete(`categories/${this.paramId}/attributes/${row.attr_id}`)
          if(res.meta.status =! 200) return this.$$message.error('删除数据失败')
          this.$message.success('已删除该分类')
          this.golist()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },  
      //修改该分类
      modParam(row){
        this.modParamVis =true
        console.log(row);
        this.modParamName.attr_name = row.attr_name
        this.modParamName.attrId = row.attr_id
      },
      //确定修改分类
      suremod(){
        this.$refs.modParamName.validate(async valid=>{
          if(!valid)return
          const {data:res} = await this.$http.put(`categories/${this.paramId}/attributes/${this.modParamName.attrId}`,
          {attr_name:this.modParamName.attr_name,attr_sel:this.isok})
          console.log(res);
          if(res.meta.status =! 200) return this.$message.error('修改数据失败')
          this.$message.success('修改分类成功')
          this.modParamVis =false
          this.golist()
        })
      },
      //取消修改
      backmod(){
        this.modParamVis =false
        this.modParamName.attr_name = ''
      }
    }
};
</script>

<style scoped>
.el-card{
  margin-top: 20px;
}
.demo-ruleForm{
  margin-top: 20px;
}
.input-new-tag{
  display: inline-block;
}
.column{
  display: flex;
}
.el-tag{
  margin: 20px;
}
</style>
